package cn.edu.cdtu.yulei.test_demo.controller;

import cn.edu.cdtu.yulei.test_demo.service.impl.InterfaceInfoImpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.util.Arrays;

@WebServlet("/userIp.do")
public class GetIpController extends HttpServlet {
    /**
     * 获取客户端地址
     * @param req
     * @param resp
     * @throws IOException
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String ip = req.getRemoteAddr();
        //判断是否为ipv6地址，如果是那么就将ipv6地址转为ipv4地址
        if(ip.contains(":")){
            InetAddress address = InetAddress.getByName(ip);
            byte[] ipv6Bytes = address.getAddress();
            byte[] ipv4Bytes = Arrays.copyOfRange(ipv6Bytes, 12, 16);
            ip = InetAddress.getByAddress(ipv4Bytes).getHostAddress();
        }
        //对接口访问次数记录
        InterfaceInfoImpl interfaceInfo = new InterfaceInfoImpl();
        interfaceInfo.addInterfaceInfo("/commService/userIp.do");
        System.out.println(ip);
    }
}
